package dk.iha;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Environment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Shared globale data/functions 
 * @author rauhe
 *
 */
public final class SharedData {
    private static final SharedData instance = new SharedData();
    public static SharedData getInstance() { return instance; }
    private final Logger log = LoggerFactory.getLogger(SharedData.class);

    private SharedData() {}
    

    private static final int MAX_NO_OF_DEBUG_STRINGS = 50;
    private Context ctx = null;
    public void setContext(Context c){
    	ctx=c;
    }
    
	private List<String> DebugData = new ArrayList<String>();
	
	public List<String> getDebugData() {
		return DebugData;
	}
	/**
	 * Adds a debug data entry
	 * @param s
	 */
	public void addDebugDataLog(String s) {
		if(DebugData.size() > MAX_NO_OF_DEBUG_STRINGS){
			//remove first item 
			DebugData.remove(0);
		}
		DebugData.add(s);
		sendDebugStateChangedBroadcast();
		log.warn(s);
	}
	/**
	 * Adds a debug data entry, with time
	 * @param s
	 */
	public void addDebugDataLog_t(String s) {
		addDebugDataLog(getDateTime() + ": " + s);
	}

	private void sendDebugStateChangedBroadcast() {
		if(ctx == null)
			return;
		Intent intent=new Intent();
		intent.setAction(SharedPreferences.BROADCAST_MESSAGE_SERVICE_DEBUG_STATE_CHANGED);
		ctx.sendBroadcast(intent);
	}

	/**
	 * Gets a string containing time
	 * good for debug statements!
	 * @return time string
	 */
	public static String getDateTime() {
		Calendar c = Calendar.getInstance();
		//System.out.println("Current time => "+c.getTime());

		SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss", Locale.US);//("yyyy-MM-dd HH:mm:ss");
		return df.format(c.getTime());
	}
	
	
	/**
	 * Checks whether GPS is enabled
	 * @return true if GPS is enabled
	 */
	public static boolean isGPSEnabled(Context ctx){
		final LocationManager manager = (LocationManager) ctx.getSystemService( Context.LOCATION_SERVICE );
	    if ( manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
	    	return true;
	    }
	    else{
	    	return false;
	    }
	}
	/**
	 * Returns Adhrence Logger's folder on the SD card 
	 * @return
	 */
	static final String getFilePath(){
		return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "AdherenceLogger";
	}
}